<script>
    $.ajax({
        url:'/cart/getlist',
        success:function (e) {
            if(!e.state){
                $('.cart-empty').removeClass('hidden');
                $('#mall-cart').addClass('hidden');
                $('#address-empty').addClass('hidden');
                $('#pay-empty').addClass('hidden');
                $('.weui-btn-area').addClass('hidden')

            }else{
                $('.cart-empty').addClass('hidden')
            }
        }
    })
</script>
<style>
    .weui-media-box:hover {background: inherit !important;  }
    #addr-content {  display: flex;  flex-wrap: wrap;  align-content: flex-start;  }
    .section-address{  float: left;  margin-left: 17px;  margin-bottom: 24px;  }
    .address-item{  height: 178px;  box-sizing: border-box;  flex: 0 0 25%;  font-size: 14px;  border: 1px solid #e0e0e0;  cursor: pointer;  position: relative;  -webkit-transition: all .4s ease;  transition: all .4s ease;  }
    .icon-delete{display: none;}
    .address-item:hover .icon-delete{display: block;}
    .address-item-new {  text-align: center;  color: #b0b0b0;  }
    .address-item dl {  padding: 15px 24px 0;  margin: 0;  }
    .address-item dt {  margin: 0 0 10px;  line-height: 30px;  }
    .address-item dd {  margin: 0;  line-height: 22px;  color: #757575;  }
    .address-item .tag {  float: right;  color: #b0b0b0;  }
    .address-item .uname {  font-size: 18px;  color: #333;  font-style: normal;  }
    .address-item-new .new-addr-icon {  display: block;  width: 30px;  height: 30px;  margin: 63px auto 8px;  font-size: 30px;  line-height: 30px;  background-color: #e0e0e0;  border-radius: 17px;  text-align: center;  -webkit-transition: all .4s ease;  transition: all .4s ease;  color: #fff;  }
    .selected {  border-color: #ff6700;  }

    /*模态框css*/
    #mask{  background-color:#ccc;  opacity:0.5;  filter: alpha(opacity=50);  position:absolute;  left:0;  top:0;  z-index:1000;  }
    #login{  position:fixed;  width: 650px;  height: 500px;  z-index:1001;  background: white;  border-radius: 15px;  }
    .weui-panel {
        background-color: #FFFFFF;
         margin-top: 0px;
        position: relative;
        overflow: hidden;
    }
</style>
<div class='menu-container' style="background: #EFEFEF">
    <div class='hidden-xs' style="height: 40px;"></div>
    <div class='container'>
        <div class='weui-flex'>
            <div class='weui-flex__item'>
                <div class='weui-cells__title'><i class='i i-cart_light'></i> 购物车</div>
                <div class='bc-list weui-cells' id="mall-cart" data-port="http://api.hongyanche.com/cart/getlist">
                    <div class='bc-list-template ' style="">
                        <div class="weui-panel weui-panel_access">
                            <!-- <div class="weui-panel__hd">图文组合列表</div> -->
                            <div class="weui-panel__bd">
                                <div href="javascript:void(0);" class="mall-cart-line weui-media-box weui-media-box_appmsg" style="align-items: flex-start;">
                                    <label class='bc-list-checkbox' style='padding-top: 6px;'>
                                        <input autocomplete='off' class='weui-check car-detail-select' name="detail" type='checkbox' />
                                        <i class="weui-icon weui-icon-checked-circle" style="font-size: 150%"></i>
                                        <detail_id list=1 class="hidden"></detail_id>
                                    </label>
                                    <div class="weui-media-box__hd">
                                        <imgurl list=none><img class="weui-media-box__thumb"
                                                               src='//api.hongyanche.com/_weyard/material/weyard-background-white.png'
                                                               alt=""></imgurl>
                                        <imgurl list=d>
                                            <imgurl list=i><img class="weui-media-box__thumb" alt=""></imgurl>
                                        </imgurl>
                                    </div>
                                    <div class="weui-media-box__bd text-nowrap">
                                        <h4 class="weui-media-box__title">
                                            <name list=1></name>
                                            <small mute class="hidden">#
                                                <detail_id list=1></detail_id>
                                            </small>
                                        </h4>
                                        <p class="weui-media-box__desc">
                                            <options list=r><span style="display: none"><config_name_cn range=d><small
                                                    mute><config_name_cn
                                                    range=1></config_name_cn></small>:</config_name_cn><option_name_cn
                                                    range=1></option_name_cn>&nbsp;</span></options>
                                        </p>
                                    </div>
                                    <div class="weui-media-box__bd text-nowrap" style="flex:1.5">
                                        <div class='weui-flex weui-flex-center'>
                                            <div class='weui-flex__item total-fee-content' align="right">
                                                <deposit list=d style="color:red">
                                                    定金 ¥
                                                    <total_fee list=f></total_fee>
                                                    <s style="color:#999"><span style="color:#999;">¥
                                                <total_fee_product list=f ></total_fee_product> </span> </s>
                                                </deposit>
                                                <discount_fee list=d style="color:red">
                                                    ¥
                                                    <total_fee list=f></total_fee>
                                                    <s style="color:#999"><span style="color:#999;">¥
                                                <total_fee_product list=f ></total_fee_product> </span> </s>
                                                </discount_fee>

                                                <product list=d><span style="color:black;">¥
                                                <total_fee list=f ></total_fee> </span>
                                                </product>

                                                <discount list=d>
                                                    <small mute style="color:#FFA500">(
                                                        <discount list=1></discount>
                                                        %)
                                                    </small>
                                                </discount>&nbsp;&nbsp;<br/>
                                            </div>

                                            <div class='weui-flex__item menu-cart-amount'>
                                                <a class='menu-cart-minus'>-</a>
                                                <input list=1 name='amount' onkeyup="this.value=this.value.replace(/[^0-9]/g,'')" onafterpaste="this.value=this.value.replace(/[^0-9]/g,'')" class="cart-pay-amount"/>
                                                <detail_id list=1 class="hidden"></detail_id>
                                                <a class='menu-cart-plus'>+</a>
                                                <total_fee list=f class="hidden"></total_fee>
                                                <a style="color:maroon" class='menu-cart-remove'>
                                                    <detail_id list=1 class="hidden"></detail_id>
                                                    <small>删除</small>
                                            </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                            </div>
                        </div>

                    </div>
                    <div style="float: right">
                        <!--优惠金额:<span id="discount_fee"></span><br/>-->
                        合计:<span id="total_fee_amount">0</span>
                        优惠金额: <span id="discount_fee">0</span>
                    </div>
                </div>
                <div  style="text-align: center;;padding:200px 0;" class='hidden cart-empty'>
                    <small mute>还没有选择任何产品 <a href='#mall' style="color:#666">去商城看看</a></small>
                </div>
                <div class='mall-cart-order-confirm' id="address-empty">
                    <div class='weui-cells__title'><i class='i i-form_light'></i> 订单确认</div>
                    <div class='weui-cells' id="mall-cart-options">
                        <div class="weui-cell">
                            <div class="weui-cell__hd">
                                收货地址:
                            </div>
                            <div class="weui-cell__bd bc-input-focus">
                                <input type="text" name="address_name" class="weui-input">
                                <input type="text" name="address_id" class="weui-input hidden" id="address_id">
                            </div>
                        </div>
                        <div class="addr-wrap">
                            <div id="addr-content">
                                <div class="section-address address-item address-item-new">
                                    <i class="i i-cart new-addr-icon"></i>
                                    增加收获地址
                                </div>
                            </div>
                        </div>
                        <div class="weui-cell">
                            <div class="weui-cell__bd bc-input-focus">
                                <textarea id="order-message" class="weui-textarea" name='message' placeholder="写点留言" rows="3"></textarea>
                            </div>
                        </div>
                        <!--<div class="weui-form-preview__ft">-->
                        <!--<a id='mall-cart-clean' class="weui-form-preview__btn weui-form-preview__btn_default" href="javascript:">清空购物车</a>-->
                        <!--<a id='cart-confirm-mobile' type="submit" class="visible-xs weui-form-preview__btn weui-form-preview__btn_primary" href="javascript:">确认</a>-->
                        <!--&lt;!&ndash; <a href='#mall_cart_pay' type="submit" class="visible-xs weui-form-preview__btn weui-form-preview__btn_primary" href="javascript:">确认</a> &ndash;&gt;-->
                        <!--</div>-->
                    </div>
                </div>

                <div class='weui-btn-area'>
                    <a class='hidde1n weui-btn weui-btn_primary' href="javascript:void (0)" id='cart-pay'>结账</a>
                </div>
            </div>
            <div style="margin:10px;"></div>
            <!--<div class='weui-flex__item mall-cart-order-confirm hidden' style='flex:0.5;'>-->
                <!--<div class='hidden-xs'>-->

                <!--</div>-->
            <!--</div>-->

        </div>
    </div>
    <div style="height: 100px;"></div>
</div>
<script>
    POST.init(document,{
        method:'change',
        url:'/mall/order_get_price',
        stop:function(e){
            var amount = e.val();
            var detail_id = e.next('detail_id').text();
            if(!amount) return true;
            if(!detail_id) return true;
        },
        input:function(e){
            var amount = $(e).val();
            var detail_id = $(e).next('detail_id').text();
            var detail = '{"'+
                detail_id+'"'+":"+amount+
                '}';
            return {detail:detail}
        },
        success:function(e,res){
                e.parents('.weui-flex-center').find('total_fee').text(res.data.info.total_fee / 100);
                e.parents('.weui-flex-center').find('total_fee_product').text(res.data.info.total_fee_product / 100);
                getPrice();
        }
    },'.cart-pay-amount');

    POST.init(document,{
        method:'click',
        url:'/cart/remove',
        text:"删除产品",
        confirm:true,
        stop:function(e){
            var detail_id = $(e).find('detail_id').html();
            if(!detail_id) return true;
        },
        input:function(e){
            var detail_id = $(e).find('detail_id').html();
            return {detail_id:detail_id}
        },
        success:function(e,res){
            LIST.reload('#mall-cart');
        }
    },'.menu-cart-remove');

    $('#mall-cart').on('click','.menu-cart-plus',function () {
        var amount = ($(this).prev().prev().val()-1)+2;
        var detail_id = $(this).prev('detail_id').text();
        var self = $(this);
        var detail = '{"'+
            detail_id+'"'+":"+amount+
        '}';
        $.ajax({
            url:'/mall/order_get_price',
            data:{
                detail:detail
            },
            success:function (e) {
                if(e.state) {
                    self.parents('.weui-flex-center').find('total_fee').text(e.data.info.total_fee / 100);
                    self.parents('.weui-flex-center').find('total_fee_product').text(e.data.info.total_fee_product / 100);
                    getPrice();
                }else{
                    alert(e.errormsg)
                }
            }
        })
    });
    $("#mall-cart").on('click','.menu-cart-minus',function () {
        var amount = $(this).next().val()-1;
        var detail_id = $(this).next().next('detail_id').text();
        var self = $(this);
        var detail = '{"'+
            detail_id+'"'+":"+amount+
            '}';
        $.ajax({
            url:'/mall/order_get_price',
            data:{
                detail:detail
            },
            success:function (e) {
                if(e.state) {
                    self.parents('.weui-flex-center').find('total_fee').text(e.data.info.total_fee / 100);
                    self.parents('.weui-flex-center').find('total_fee_product').text(e.data.info.total_fee_product / 100);
                    getPrice();
                }else{
                    alert(e.errormsg);
                }
            }
        })
    });
    /**
     * @param {num} 数字或者字符串
     * @return {num} 返回带有.00的字符串数字
     * */
    function getFloatStr(num){
        num += '';
        num = num.replace(/[^0-9|\.]/g, ''); //清除字符串中的非数字非.字符

        if(/^0+/) //清除字符串开头的0
            num = num.replace(/^0+/, '');
        if(!/\./.test(num)) //为整数字符串在末尾添加.00
            num += '.00';
        if(/^\./.test(num)) //字符以.开头时,在开头添加0
            num = '0' + num;
        num += '00';        //在字符串末尾补零
        num = num.match(/\d+\.\d{2}/)[0];
        return num;
    }
//    $("#mall-cart").on('bc-list-success', function () {
        function getPrice() {
//            $('#mall-cart').on('change','input[name="detail"]', function () {
                var detail = {};
                $('input[name="detail"]:checked').each(function (index, el) {
                    var detailId = $(this).next().next().text();
                    var amount = $(this).parents().find('input[name="amount"]').val();
                    detail[detailId] = amount;
                });
            if (JSON.stringify(detail) !== '{}') {
                $.ajax({
                    type: 'POST',
                    url: '/mall/order_get_price',
                    data: {
                        detail: JSON.stringify(detail)
                    },
                    success: function (data) {
                        $('#total_fee_amount').html(getFloatStr(data.data.info.total_fee / 100));
                        $('#discount_fee').html(getFloatStr(data.data.info.discount_fee / 100));
                        $('#total_fee_amount').css('color','#ff6700');
                        $('#discount_fee').css('color','#ff6700');
                    }
                })
            } else {
                $('#discount_fee').html(0);
                $('#total_fee_amount').html(0);
                $('#total_fee_amount').css('color','black');
                $('#discount_fee').css('color','black');
                return;
            }
//            });
        }

    $('#mall-cart').on('change','input[name="detail"]', function () {
        getPrice();
    });
//    });


    (function (w, u) {
        const addrContent = $('#addr-content');  // 收货地址列表
        // GET获取数据
        function getAddr(uri) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: uri,
                    type: 'GET',
                    success: function (data) {
                        let datas = data.data.list;
                        resolve(datas)
                    },
                    error: function (err) {
                        reject(err)
                    }
                })
            })
        };
        // 模态框
        function openNew() {
            //获取页面的高度和宽度
            var sWidth=document.body.scrollWidth;
            var sHeight=document.body.scrollHeight;

            //获取页面的可视区域高度和宽度
            var wHeight=document.documentElement.clientHeight;

            var oMask=document.createElement("div");
            oMask.id="mask";
            oMask.style.height=sHeight+"px";
            oMask.style.width=sWidth+"px";
            document.body.appendChild(oMask);
            var oLogin=document.createElement("div");
            oLogin.id="login";
            oLogin.innerHTML="<div class='loginCon'><div id='close' style='position: absolute; right: 0; top: 0;'><i class='weui-icon weui-icon-cancel weui-icon-original' style='font-size: 25px;'></i></div></div>";
            document.body.appendChild(oLogin);
            //获取登陆框的宽和高
            var dHeight=oLogin.offsetHeight;
            var dWidth=oLogin.offsetWidth;
            //设置登陆框的left和top
            oLogin.style.left=sWidth/2-dWidth/2+"px";
            oLogin.style.top=wHeight/2-dHeight/2+"px";
            //点击关闭按钮
            var oClose=document.getElementById("close");

            //点击登陆框以外的区域也可以关闭登陆框
            oClose.onclick=oMask.onclick=function(){
                document.body.removeChild(oLogin);
                document.body.removeChild(oMask);
            };
        }

        function getInfo() {  // 获取所有地址信息并插入到HTML中
            getAddr('/mall/address_list').then((data) => {
                console.log(data);
                for (let i = 0; i < data.length; i++) {
                    if (data[i].default == 1) {
                        $('.bc-input-focus').find('input.weui-input').val(data[i].addressfull);
                        addrContent.find('.address-item-new').before(`
                            <div style="position: relative" class="js-address section-address address-item selected" aid="${data[i].address_id}">
                                <dl>
                                    <dt>
                                    <i class="weui-icon weui-icon-cancel weui-icon-original icon-delete" style="font-size: 25px; position: absolute; right: 5px; bottom: 10px;" aid="${data[i].address_id}"></i>
                                    <span class="tag">默认</span>
                                    <em class="uname">${data[i].address_name}</em>
                                    </dt>
                                    <dd class="utel">${data[i].address_tel}</dd>
                                    <dd class="uaddress">${data[i].addressfull}</dd>
                                </dl>
                            </div>
                    `)
                    } else if (data[i].default == u) {
                        addrContent.find('.address-item-new').before(`
                            <div style="position: relative" class="js-address section-address address-item" aid="${data[i].address_id}">
                                <dl>
                                    <dt>
                                    <i class="weui-icon weui-icon-cancel weui-icon-original icon-delete" style="font-size: 25px; position: absolute; right: 5px; bottom: 10px;" aid="${data[i].address_id}"></i>
                                    <em class="uname">${data[i].address_name}</em>
                                    </dt>
                                    <dd class="utel">${data[i].address_tel}</dd>
                                    <dd class="uaddress">${data[i].addressfull}</dd>
                                </dl>
                            </div>
                        `)
                    }
                }
            }).catch((err) => {
                console.log(err);
                $.toptip('获取数据失败', err);
            })
        }
        getInfo();

        function setAddress() {
            addrContent.on('click', '.js-address', function () {
                $('.address-item').removeClass('selected');
                $(this).addClass('selected');
                let addressId = $(this).attr('aid');
                let addressDetails = $(this).find('dd.uaddress').text();
                $('.bc-input-focus').find('input.weui-input').val(addressDetails);
                $('.bc-input-focus').find('#address_id').val(addressId);
            })
        }
        setAddress();
        // 新增收货地址
        function  addAddress() {
            addrContent.on('click', '.address-item-new', function () {
                openNew();
                $('#login').append(`
                        <div class='weui-flex__item'>
        <div class='weui-cells__title'>收货地址编辑</div>
        <div class='weui-cells bc-district'>
            <div class='weui-cell'>
                <div class='weui-cell__hd'>
                    <label class='weui-label'>姓名</label>
                </div>
                <div class='weui-cell__bd'>
                    <input id="name-modify" class='user-address-modify weui-input' info=1 name='address_name' placeholder="请输入姓名" />
                </div>
            </div>
            <div class='weui-cell'>
                <div class='weui-cell__hd'>
                    <label class='weui-label'>电话</label>
                </div>
                <div class='weui-cell__bd'>
                    <input class='user-address-modify weui-input' info=1 name='address_tel' placeholder="请输入电话号码" />
                </div>
            </div>
            <div class='weui-cell'>
                <div class='weui-cell__hd'>
                    <label class='weui-label'>座机</label>
                </div>
                <div class='weui-cell__bd'>
                    <input class='user-address-modify weui-input' info=1 name='landline' placeholder="例:023-12345678" />
                </div>
            </div>
            <div class='weui-cell'>
                <div class='weui-cell__hd'>
                    <label class='weui-label'>省市</label>
                </div>
                <div class='weui-cell__bd'>

                    <select class='user-address-modify weui-input' id='a'  in1fo=1 name='province' placeholder="请输入所在省市" ></select>
                    </div>
                    </div>
                    <div class='weui-cell'>
                    <div class='weui-cell__hd'>
                    <label class='weui-label'>市区</label>
                    </div>
                    <div class='weui-cell__bd'>
                    <select class='user-address-modify weui-input' id="b"  info=1 name='city' placeholder="请输入所在市区" ></select>
                    </div>
                    <div class='weui-cell__hd'>
                    <label class='weui-label'>区县</label>
                    </div>
                    <div class='weui-cell__bd'>

                    <select class='user-address-modify weui-input' id ="c" info=1 name='district' placeholder="请输入所在区县" ></select>
                    </div>
                    </div>
                    <div class='weui-cell'>
                    <div class='weui-cell__hd'>
                    <label class='weui-label'>详细地址</label>
                    </div>
                    <div class='weui-cell__bd'>
                    <input class='user-address-modify weui-input' info=1 name='address' placeholder="请输入详细地址" />
                    </div>
                    </div>
                    <div class='weui-cell'>
                    <div class='weui-cell__hd'>
                    <label class='weui-label'>邮编</label>
                    </div>
                    <div class='weui-cell__bd'>
                    <input class='user-address-modify weui-input' info=1 name='address_code' placeholder="请输入邮编" />
                    </div>
                    </div>
                    </div>
                    <div class='weui-btn-area'>
                    <a id='address-add-confirm' href="javascript:;" class="weui-btn weui-btn_fle1x weui-btn_primary">添加</a>
                    </div>
                    </div>
                `);
                DISTRICT.load('.bc-district');
                POST.init('#address-add-confirm',{
                    text:"添加",
                    url:'/mall/address_create',
                    input:function(){
                        var r = {};
                        $('.user-address-modify').each(function(index, el) {
                            r[$(el).attr('name')] = $(el).val();
                        });
                        return r;
                    },
                    success:function(){
                        $('.user-address-modify').each(function(index, el) {
                            $(el).val('');
//                            $('body').remove('#mask');
//                            $('body').remove('#login');
                        });
                        $('#addr-content').find('.js-address').remove();
                        getInfo();
                        $('body').find('#mask').remove();
                        $('body').find('#login').remove();
                    }
                });
            });
        }
        addAddress();

        // 删除

        $('#addr-content').on('click','.icon-delete' ,function () {
            var aID = $(this).attr('aid');
            var isDelete = confirm('是否确认删除该地址？');
            if (isDelete) {
                $.ajax({
                    url: '/mall/address_remove',
                    type: 'POST',
                    data: {address_id: aID},
                    success: function (ret) {
                        w.location.reload();
                    }
                })
            }
        })
    })(window, undefined);
    // 付款 #mall_cart_pay
    POST.init(document,{
        method:'click',
        url:'/mall/order_create',
        stop:function(e){
            var detail = {};
            $('input[name="detail"]:checked').each(function (index, el) {
                var detailId = $(this).next().next().text();
                var amount = $(this).parents().find('input[name="amount"]').val();
                detail[detailId] = amount;
            });
            if (JSON.stringify(detail) === '{}') {
                return true;
            }
        },
        input:function(e){
            var detail = {};
            var aID = $('.selected').attr('aid');
            var messageContent = $('#order-message').val();
            var amounts = 0;
            $('input[name="detail"]:checked').each(function (index, el) {
                var detailId = $(this).next().next().text();
                var amount = $(this).parents().find('input[name="amount"]').val();
                amounts ? amounts = parseInt(amounts) + parseInt(amount) : amounts = parseInt(amount);
                detail[detailId] = amount;
            });
            localStorage.amount = amounts;
            return {detail:JSON.stringify(detail), address_id: aID, content: messageContent}
        },
        success:function(e,res){
            if(res.state) {
                localStorage.address = res.data.info.address;
                localStorage.mall_name = res.data.info.mall_name;
                localStorage.order_id = res.data.info.order_id;
                localStorage.total_fee = res.data.info.total_fee;
                localStorage.addressName = res.data.info.address_name;
                window.location.href = '/home#mall_cart_pay'
            }else{
                alert(res.errormsg)
            }
        }
    },'#cart-pay');

</script>
